<template>
  <el-dialog v-model="dialog" title="摄像头配置" width="700px">
    <div style="max-height: 400px; overflow-y: auto; display: flex; justify-content: center;">
      <el-form ref="elForm" :model="form" :rules="rules" label-position="top" style="width: 350px;">
        <el-form-item prop="camera">
          <el-input type="textarea" :rows="6" v-model.trim="form.camera"></el-input>
        </el-form-item>
      </el-form>
      <div class="mL20">
        <div>摄像头配置格式请严格按照如下格式进行填写:</div>
        <pre>
[
 {
  "SN":"SN序列号",
  "NAME":"某某学校厨房01"
 },
 {
  "SN":"SN序列号",
  "NAME":"某某学校厨房02"
 }
]
        </pre>
      </div>
    </div>
    <template #footer>
      <el-button type="primary" @click="confirmUpdate">保存</el-button>
      <el-button @click="dialog = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
  
  import {
    ref,
    reactive,
    inject,
    nextTick,
    getCurrentInstance
  } from 'vue'
  import {
    Plus
  } from '@element-plus/icons-vue'
  
  const $message = inject('$message');
  const $post = inject('$post');
  const $upload = inject('$upload');
  const {
    ctx
  } = getCurrentInstance();
  
  const dialog = ref(false);
  
  const form = reactive({
    guid: '',
    camera: ''
  })
  
  const rules = {
    camera: [{
      validator: (rule, value, callback) => {
        if (value) {
          try {
            let arr = JSON.parse(value);
            if (!(arr instanceof Array)) {
              return callback(new Error('请输入正确的格式'));
            } else {
              for (let index in arr) {
                index = parseInt(index);
                let obj = arr[index];
                if (!obj.SN) {
                  return callback(new Error(`请输入第${index + 1}个摄像头的SN序列号`));
                }
                if (!obj.NAME) {
                  return callback(new Error(`请输入第${index + 1}个摄像头的名称`));
                }
              }
            }
          } catch(e) {
            return callback(new Error('请输入正确的格式'));
          }
        }
        callback();
      },
      trigger: 'blur'
    }]
  }
  
  // 确认保存
  const confirmUpdate = () => {
    ctx.$refs.elForm.validate(res => {
      $post('/consumer/byCamera', form).then(res => {
        $message.success('修改成功');
        dialog.value = false;
        ctx.$refs.elForm.resetFields();
      })
    })
  }
  
  defineExpose({
    // 展示模态框
    show: guid => {
      dialog.value = true;
      $post('/v2/consumer/byOpt', {
        guid
      }).then(res => {
        form.guid = guid;
        form.camera = res.data.camera;
        nextTick(ctx.$refs.elForm.clearValidate);
      })
    }
  })
  
</script>

<style>
</style>
